import LoginFormPage from "../pages/AdminPages/LoginFormPage.tsx";
import AuthPage from "../pages/AdminPages/AuthPage.tsx";
import AdminLoader from "../component/AdminLoader/index.tsx";
import { useState, useEffect, useCallback } from "react";
import type { AuthMode } from "../component/AuthForm/index.tsx";
import type { AuthFormConfig } from "../pages/AdminPages/AuthPage.tsx";

interface RouterOptions {
  /* 路由模式 */
  mode?: 'hash' | 'history';
  /* 路由加载器 默认是 admin */
  loaderPath?: string;
  /* 认证模式 */
  authMode?: AuthMode;
  /* 认证表单配置 */
  authConfig?: AuthFormConfig;
  /* 是否使用 SPA 路由 */
  useSpaRouter?: boolean;
}

export default function useRouterCreate(options: RouterOptions = { 
  mode: 'hash', 
  loaderPath: 'admin', 
  authMode: 'login-register',
  useSpaRouter: false 
}) {
  // 根据模式获取当前路径
  const getCurrentPath = useCallback(() => {
    if (options.useSpaRouter) {
      return window.location.pathname;
    }
    if (options.mode === 'hash') {
      return window.location.hash.slice(1) || '/';
    }
    return window.location.pathname;
  }, [options.mode, options.useSpaRouter]);

  const [currentPath, setCurrentPath] = useState(getCurrentPath());

  useEffect(() => {
    const handleLocationChange = () => {
      setCurrentPath(getCurrentPath());
    };

    if (options.useSpaRouter) {
      // 监听 Remix 路由变化
      window.addEventListener('popstate', handleLocationChange);
      return () => window.removeEventListener('popstate', handleLocationChange);
    } else if (options.mode === 'hash') {
      window.addEventListener('hashchange', handleLocationChange);
      return () => window.removeEventListener('hashchange', handleLocationChange);
    } else {
      window.addEventListener('popstate', handleLocationChange);
      return () => window.removeEventListener('popstate', handleLocationChange);
    }
  }, [options.mode, options.useSpaRouter, getCurrentPath]);

  const navigate = useCallback((path: string) => {
    if (options.useSpaRouter) {
      // 使用 Remix 的路由导航
      window.history.pushState({}, '', path);
      setCurrentPath(path);
      // 触发 popstate 事件以通知 Remix 路由变化
      window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
    } else if (options.mode === 'hash') {
      window.location.hash = path;
    } else {
      window.history.pushState({}, '', path);
      setCurrentPath(path);
    }
  }, [options.mode, options.useSpaRouter]);

  // 路由映射
  const routes = {
    '/': <AuthPage 
      loaderPath={options.loaderPath} 
      authMode={options.authMode}
      authConfig={options.authConfig}
    />,
    [`/${options.loaderPath}`]: <AdminLoader />,
  };

  // 如果使用 Remix 路由，返回 null 让 Remix 处理路由
  const element = options.useSpaRouter 
    ? null 
    : (routes[currentPath as keyof typeof routes] || 
        <AuthPage 
          loaderPath={options.loaderPath} 
          authMode={options.authMode}
          authConfig={options.authConfig}
        />);

  return {
    element,
    navigate,
    currentPath
  };
}
